package com.wgts.wgts.netmodle;

import android.util.Log;
import android.widget.Toast;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeoutException;

import rx.Subscriber;

/**
 */

public abstract class HttpResultSubscriber<T> extends Subscriber<HttpResult<T>> {
    @Override
    public void onNext(HttpResult<T> t){
        if (t.isSuccess()) {
            onSuccess(t.getResult());
        } else {
            _onError(Integer.valueOf(t.getCode()), t.getMessage());
        }
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        //在这里做全局的错误处理
        if (e instanceof ConnectException ||
                e instanceof SocketTimeoutException ||
                e instanceof TimeoutException) {


            if(NetWorkFactory.getsOkHttpClient() != null){
                NetWorkFactory.getsOkHttpClient().dispatcher().cancelAll();
            }

            if (System.currentTimeMillis() - NetWorkFactory.getNetTime() > 5000) {
                NetWorkFactory.setNetTime(System.currentTimeMillis());
                switch (NetWorkFactory.getIndexForHost()){
                    case 0:
                        NetWorkFactory.setIndexForHost(1);
                        Log.e("===============", "0---->1");
                        break;
                    case 1:
                        NetWorkFactory.setIndexForHost(2);
                        Log.e("===============", "1---->2");
                        break;
                    case 2:
                        NetWorkFactory.setIndexForHost(3);
                        Log.e("===============", "2---->3");
                        break;
                    case 3:
                        NetWorkFactory.setIndexForHost(0);
                        Log.e("===============", "3---->0");
                        break;
                }
            }


            //网络错误
            _onError(-9999, "网络链接超时,请稍后重试");
        }else if (e instanceof ResultException) {
            //自定义的ResultException
            //由于返回200,300返回格式不统一的问题，自定义GsonResponseBodyConverter凡是300的直接抛异常
            _onError(((ResultException) e).getErrCode(),((ResultException) e).getMsg());
        }else{
            _onError(404, "网络链接超时,请稍后重试");
        }
    }


    public abstract void onSuccess(T t);

    public abstract void _onError(int status,String msg);
}
